<script setup lang="ts" name="EaWorkType">
import { Plus, Edit, Search, ArrowDown, Picture } from '@element-plus/icons-vue'
import type { EaWorkTreeModel, EaWorkType } from './type'
import Detail from './Detail.vue'
import Form from './Form.vue'
import WorkTypeTree from '@/views/ea/ea-work-type/Tree.vue'

const changeCurrentNode = (currentNodeKey?: string) => {
  queryParam.parentId = currentNodeKey ?? ''
  onSearch()
}
import { buildImgSrc, imageBindSrc } from '@/utils/file'
import { checkPermission } from '@/utils/permission'

const baseApi = '/ea/ea-work-type'

const { getList, queryParam, dataList, loading, onSearch, pagination, remove, batchRemove, resetFilter } =
  useList<EaWorkTreeModel>({
    baseApi,
    listApi: `${baseApi}/tree`
  })
// const { queryParam, loading, dataList, pagination, getList, onSearch, resetFilter, remove, batchRemove } =
//   useList<EaWorkType>({ baseApi, initQueryParam: { parentId: '0' } })
console.log(dataList)
defineExpose({
  refresh: onSearch,
  addCondition: (key: keyof EaWorkType, value: any, refresh = false) => {
    queryParam[key] = value
    if (refresh) onSearch()
  }
})

const { initRelatedData, relatedData } = useOption({
  load: {
    parentIdOptions: {
      type: 'EaWorkType',
      label: 'title',
      parent: 'parentId',
      parentPath: 'parentIdsPath',
      lazyChild: false
    }
  }
})
initRelatedData()

const sortChange = ({ column, prop, order }: { column: { sortBy?: string }; prop: string; order: string }) => {
  let orderBy: 'ASC' | 'DESC' | undefined
  switch (order) {
    case 'ascending':
      orderBy = 'ASC'
      break
    case 'descending':
      orderBy = 'DESC'
      break
    default:
      orderBy = undefined
  }
  pagination.orderBy = orderBy ? `${column.sortBy ?? prop}:${orderBy}` : undefined
  onSearch()
}

const formRef = ref()
const formTitle = ref('')
const submitting = ref(false)
const formVisible = ref(false)
const addSustainably = ref<boolean>(false)

const openForm = (id?: string) => {
  if (id) {
    addSustainably.value = false
    formTitle.value = '编辑'
  } else {
    addSustainably.value = true
    formTitle.value = '新建'
  }
  formVisible.value = true

  nextTick(() => formRef.value?.init(id))
}

const closeForm = () => {
  formVisible.value = false
}

const submit = (goOn = false) => {
  formRef.value?.submit()?.then((result: boolean) => {
    if (result) {
      if (!goOn) {
        formVisible.value = false
      }
      formRef.value?.reset()
    }
  })
}

const detailRef = ref()
const detailVisible = ref(false)
const dataId = ref('')

const openDetail = (id: string) => {
  dataId.value = id
  detailVisible.value = true

  nextTick(() => detailRef.value?.init(id))
}

const closeDetail = () => {
  detailVisible.value = false
}
const closeDetailAndOpenForm = () => {
  detailVisible.value = false
  openForm(dataId.value)
}

const handleOperation = (code: string, value?: string | string[]) => {
  switch (code) {
    case 'detail':
      openDetail(value as string)
      break
    case 'create':
    case 'update':
      openForm(value as string)
      break
    case 'remove':
      remove(value as string)
      break
    case 'batchRemove':
      batchRemove(value as string[])
      break
    default:
      throw new Error(`不存在的操作编码${code}!`)
  }
}

const sum = (prop: keyof EaWorkType, fractionDigits?: number) =>
  Number(
    (dataList ?? [])
      .map(e => Number(e[prop] ?? 0))
      .reduce((e1, e2) => e1 + e2, 0)
      .toFixed(fractionDigits)
  )

const ave = (prop: keyof EaWorkType, fractionDigits?: number) =>
  Number(
    ((dataList ?? []).map(e => Number(e[prop] ?? 0)).reduce((e1, e2) => e1 + e2, 0) / (dataList ?? []).length).toFixed(
      fractionDigits
    )
  )

const refreshData = (haveNewData?: boolean) => {
  haveNewData ? onSearch() : getList()
}

const router = useRouter()

const activated = () => {
  nextTick(() => {
    const query = router.currentRoute.value.query
    for (const queryKey in query) {
      queryParam[queryKey as keyof EaWorkType] = query[queryKey] as any
    }

    onSearch()
  })
}

router.currentRoute.value.meta.keepAlive ? onActivated(activated) : activated()

import type Node from 'element-plus/es/components/tree/src/model/node'
import type { DragEvents } from 'element-plus/es/components/tree/src/model/useDragNode'
import type { AllowDropType, NodeDropType } from 'element-plus/es/components/tree/src/tree.type'

const handleDragStart = (node: Node, ev: DragEvents) => {}
const handleDragEnter = (draggingNode: Node, dropNode: Node, ev: DragEvents) => {}
const handleDragLeave = (draggingNode: Node, dropNode: Node, ev: DragEvents) => {}
const handleDragOver = (draggingNode: Node, dropNode: Node, ev: DragEvents) => {}
const handleDragEnd = (draggingNode: Node, dropNode: Node, dropType: NodeDropType, ev: DragEvents) => {}
const handleDrop = (draggingNode: Node, dropNode: Node, dropType: NodeDropType, ev: DragEvents) => {
  const parent = dataList?.find(item => item.id === draggingNode?.data?.parentId)

  const children = parent?.children?.map((child, childIndex) => {
    return {
      ...child,
      sort: childIndex
    }
  })

  api.put(`/ea/ea-work-type/updateBatch`, {
    eaWorkTypes: children
  })
}
const allowDrop = (draggingNode: Node, dropNode: Node, type: AllowDropType) => {
  if (draggingNode.data.parentId === dropNode.data.parentId && draggingNode.level === dropNode.level) {
    return type === 'prev' || type === 'next'
  } else {
    return false
  }
}
const allowDrag = (draggingNode: Node) => {
  return draggingNode.data.parentId !== '0'
}
</script>

<template>
  <el-container class="el-container">
    <!-- <el-aside class="el-aside" width="240px">
      <work-type-tree @click-node="changeCurrentNode" />
    </el-aside> -->
    <el-container>
      <div class="list-container">
        <div class="list-page">
          <el-space wrap class="list-operation">
            <el-button v-has-permission="'create'" type="primary" :icon="Plus" @click="handleOperation('create')">
              新建
            </el-button>
            <div />
            <!-- <el-space>
              <span class="search">
                <el-tree-select
                  v-model="queryParam.parentId"
                  placeholder="上级"
                  :data="relatedData.parentIdOptions"
                  filterable
                  default-expand-all
                  check-strictly
                  clearable
                  @change="onSearch"
                />
              </span>
              <el-button :icon="Search" type="primary" @click="onSearch">查询</el-button>
              <el-button title="重置查询条件" @click="resetFilter">重置</el-button>
            </el-space> -->
          </el-space>
          <el-tree
            style="width: 600px; margin: 0 auto"
            :allow-drop="allowDrop"
            :allow-drag="allowDrag"
            :data="dataList"
            draggable
            default-expand-all
            :props="{
              label: 'title'
            }"
            node-key="id"
            @node-drag-start="handleDragStart"
            @node-drag-enter="handleDragEnter"
            @node-drag-leave="handleDragLeave"
            @node-drag-over="handleDragOver"
            @node-drag-end="handleDragEnd"
            @node-drop="handleDrop"
          >
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <span>{{ node.label }}</span>
                <el-space>
                  <el-button
                    v-has-permission="'detail'"
                    type="primary"
                    link
                    size="small"
                    @click="handleOperation('detail', data.id)"
                  >
                    详情
                  </el-button>
                  <el-button link size="small" @click.stop="handleOperation('update', data.id)">编辑</el-button>
                  <el-button link size="small" type="danger" @click.stop="handleOperation('remove', data.id)"
                    >删除</el-button
                  >
                </el-space>
              </div>
            </template>
          </el-tree>

          <el-pagination
            v-if="pagination.total"
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 15, 20, 30, 50, 100]"
            small
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="getList()"
            @current-change="getList()"
          />

          <el-dialog v-model="formVisible" destroy-on-close width="60%" :title="formTitle" draggable @close="closeForm">
            <Form
              ref="formRef"
              @submitting="(val: boolean) => (submitting = val)"
              @complete="(id?: string, isNew?: boolean) => refreshData(isNew)"
            />

            <template #footer>
              <el-button @click="closeForm">取消</el-button>
              <el-button v-show="addSustainably" type="primary" :loading="submitting" @click="submit(true)">
                保存并继续
              </el-button>
              <el-button type="primary" :loading="submitting" @click="submit()">保存</el-button>
            </template>
          </el-dialog>

          <el-dialog v-model="detailVisible" width="60%" title="详情" draggable @close="closeDetail">
            <Detail ref="detailRef" />

            <template #footer>
              <el-button
                v-has-permission="'update'"
                plain
                :icon="Edit"
                type="primary"
                style="position: absolute; left: var(--el-dialog-padding-primary)"
                @click="closeDetailAndOpenForm"
              >
                编辑
              </el-button>
              <el-button @click="closeDetail">关闭</el-button>
            </template>
          </el-dialog>
        </div>
      </div>
    </el-container>
  </el-container>
</template>

<style scoped lang="scss">
.el-container {
  height: 100%;
  padding-bottom: 20px;
}
.el-aside {
  box-sizing: border-box;
  border-right: solid 1px var(--el-menu-border-color);
}
.list-container {
  width: 100%;
  height: 100%;
}
.option {
  display: flex;
  justify-content: space-between;

  .ext {
    font-size: var(--el-font-size-extra-small);
    color: var(--el-text-color-secondary);
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  border-bottom: 1px solid #f4f4f4;
}
</style>
